<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Address;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class  AddressController extends Controller
{	
	// 执行地址添加操作
	public function insert(Request $request){
		// dd($request->all());
		//判断是否为默认地址
		if($request->input('isdefault') == 1){
			DB::table('addresses')->update(['isdefault'=>0]);
		}
		$address = new Address;
		//创建数据
		$address->sheng = $request->input('sheng');
		$address->shi = $request->input('shi');
		$address->xian = $request->input('xian');
		$address->jiedao = $request->input('jiedao');
		$address->phone = $request->input('phone');
		$address->getman = $request->input('getman');
		$address->isdefault = $request->input('isdefault');
		$address->user_id = session('id');
		
		//执行插入
		if($address->save()){
			return back();
		}
		else{
			echo 'no';
		}
		
	}
	//通过用户id获取收货地址
	public static function getAllAddressById($id){
		return Address::where('user_id',$id)->get();
	}

	//显示地址列表
	public function addlist(){
		$did = DB::table('gonggao')->get();
		$dif = DB::table('link')->get();
		$address = AddressController::getAllAddressById(session('id'));
		// dd($address);
		//解析模板
		return  view('geren.addlist',['address'=>$address,'aaa'=>$did,'lianjie'=>$dif]);
	}
	//删除地址
	public function delete(Request $request){
		$id=$request->input('id');

		$num = DB::table('addresses')->where('id',$id)->delete();
		echo $num;
		// echo 1;
	}
	//修改地址
	public function edit($id,Request $request){
		// $id=$request->input('id');
		// dd($id);
		$address = Address::where('id',$id)->first();
		// dd($address);
		return view('address.edit',['address'=>$address]); 
	}

	//更新地址
	public function update(Request $request){
		$isdefault =$request->input('isdefault');
		// dd($id);
		// dd($request->all());
		//判断是否为默认地址 
		$id = $request->input('id');
		// dd($id);
		if($request->input('isdefault') == 1){
			DB::table('addresses')->update(['isdefault'=>0]);
		}
		$data = $request->except('_token');
		// dd($data);
		$num = Address::where('id',$id)->update($data);
		if($num){
		// dd($address);
			return redirect('/address/addlist');

		} 
		else{
			return back();
		}
	}
}

